package eu.jba.denshijisho.adapter;

import java.util.List;

import eu.jba.denshijisho.R;
import eu.jba.denshijisho.entity.Card;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class CardAdapter extends ArrayAdapter<Card>{
	
	private Context context;
	private int layoutResourceId;
	private List<Card> data;
	
	public CardAdapter(Context context,
			int layoutResourceId, List<Card> data) {
		super(context, layoutResourceId, data);
		this.context = context;
		this.layoutResourceId = layoutResourceId;
		this.data = data;
	}
	
	public void setData(List<Card> data){
		this.data = data;
	}
	
	private void setHolderValues(View row, CardHolder holder, boolean word){
		holder.svkText = (TextView)row.findViewById(
			word ? R.id.svk_text_view_item_row : R.id.svk_text_view_item_row1
		);
		holder.kanaText = (TextView)row.findViewById(
			word ? R.id.kana_text_view_item_row : R.id.kana_text_view_item_row1
		);
		holder.kanjiText = (TextView)row.findViewById(
			word ? R.id.kanji_text_view_item_row : R.id.kanji_text_view_item_row1 
		);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent){
		View row = convertView;
		CardHolder holder = new CardHolder();
		Card card = data.get(position);
		final LayoutInflater inflater = ((Activity)context).getLayoutInflater();
		
		if( row == null ){
			row = inflater.inflate(layoutResourceId, parent, false);
			setHolderValues(row, holder, true);
			row.setTag( holder );
		}else{
			if( card.getType().equals("Phrase")){
				row = inflater.inflate( R.layout.listview_item_row1, parent, false);
				setHolderValues(row, holder, false);
				row.setTag( holder );
			}else{
				row = inflater.inflate(layoutResourceId, parent, false);
				setHolderValues(row, holder, true);
				row.setTag( holder );
			}
		}
		
		holder.svkText.setText( card.getSvkWord() );
		holder.kanaText.setText( card.getKanaWord() );
		holder.kanjiText.setText(card.getKanji());
		return row;
	}

	private static class CardHolder{
		private TextView svkText;
		private TextView kanaText;
		private TextView kanjiText;
	}
}
